//
//  RunViewController.m
//  SportSocial
//
//  Created by yull on 15/1/8.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "RunViewController.h"
#import "BMapKit.h"
#import "UIColor+MethodExt.h"
#import "PhotoNet.h"
#import <ShareSDK/ShareSDK.h>
#import "ShareNet.h"

#import "WXApi.h"
#import "UIImage+resize.h"

@interface RunViewController () <BMKMapViewDelegate,BMKLocationServiceDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIImageView *bottomView;
@property (nonatomic, strong) UILabel *distanceTagLabel;
@property (nonatomic, strong) UILabel *distanceLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *calorieLabel;

@property (nonatomic, strong) UIButton *runButton;
@property (nonatomic, strong) UIButton *photoButton;
@property (nonatomic, strong) UIButton *shareButton;

@property (nonatomic, strong) BMKMapView *runMapView;
@property (nonatomic, strong) BMKLocationService *locationService;

@property (nonatomic, assign) BOOL haveSetCenter;
@property (nonatomic, assign) BOOL isRunning;
@property (nonatomic, strong) NSMutableArray *locationArray;
@property (nonatomic, assign) CGFloat runDistance;
@property (nonatomic, assign) NSInteger runTime;
@property (nonatomic, strong) NSTimer *runTimer;

@property (nonatomic, strong) NSString *shareUrl;

@end

@implementation RunViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initNaviBar];
    
    [self initBottomView];
    
    [self initMapView];
    
    [self updateDistanceLabelWithDistance:0.0f];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.runMapView.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.runMapView.delegate = nil;
}

- (void)initNaviBar
{
    [self addCommonBackButton];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"跑步计算器";
}

- (void)initBottomView
{
    CGRect rect = CGRectMake(0, self.view.height-Navibar_Height-190, self.view.width, 190);
    self.bottomView = [[UIImageView alloc] initWithFrame:rect];
    self.bottomView.image = [UIImage imageNamed:@"jibuqi_bg"];
    self.bottomView.userInteractionEnabled = YES;
    [self.view addSubview:self.bottomView];
    
    rect = CGRectMake(25, -30, 60, 60);
    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:rect];
    iconImageView.image = [UIImage imageNamed:@"run_icon"];
    [self.bottomView addSubview:iconImageView];
    
    rect = CGRectMake(0, 20, 0.0f, 30.0f);
    self.distanceLabel = [[UILabel alloc] initWithFrame:rect];
    self.distanceLabel.backgroundColor = [UIColor clearColor];
    self.distanceLabel.font = [UIFont systemFontOfSize:27.0f];
    self.distanceLabel.textColor = [UIColor colorWithHexString:@"cf222a"];
    [self.bottomView addSubview:self.distanceLabel];
    
    rect.origin.y = 30;
    rect.size.height = 20;
    self.distanceTagLabel = [[UILabel alloc] initWithFrame:rect];
    self.distanceTagLabel.backgroundColor = [UIColor clearColor];
    self.distanceTagLabel.text = @"公里数";
    self.distanceTagLabel.font = [UIFont systemFontOfSize:18.0f];
    self.distanceTagLabel.textColor = self.distanceLabel.textColor;
    self.distanceTagLabel.width = [self.distanceTagLabel sizeThatFits:CGSizeZero].width;
    [self.bottomView addSubview:self.distanceTagLabel];
    
    rect.origin.x = self.view.width / 2 + 30;
    rect.size.width = self.view.width - rect.origin.x;
    self.timeLabel = [[UILabel alloc] initWithFrame:rect];
    self.timeLabel.backgroundColor = [UIColor clearColor];
    self.timeLabel.font = [UIFont systemFontOfSize:18.0f];
    self.timeLabel.textColor = self.distanceLabel.textColor;
    self.timeLabel.text = @"计时 00:00";
    [self.bottomView addSubview:self.timeLabel];
    
    rect = CGRectMake(0, self.timeLabel.bottom + 10, self.view.width, self.timeLabel.height);
    self.calorieLabel = [[UILabel alloc] initWithFrame:rect];
    self.calorieLabel.backgroundColor = [UIColor clearColor];
    self.calorieLabel.font = self.timeLabel.font;
    self.calorieLabel.textColor = self.distanceLabel.textColor;
    self.calorieLabel.textAlignment = NSTextAlignmentCenter;
    self.calorieLabel.text = @"卡路里消耗了0大卡";
    [self.bottomView addSubview:self.calorieLabel];
    
    rect = CGRectMake(0, self.calorieLabel.bottom + 15, 75, 75);
    self.runButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.runButton.frame = rect;
    self.runButton.centerX = self.bottomView.width / 2;
    self.runButton.backgroundColor = [UIColor clearColor];
    [self.runButton setTitle:@"跑步开始" forState:UIControlStateNormal];
    [self.runButton setTitleColor:RGB(196, 29, 32) forState:UIControlStateNormal];
    self.runButton.titleLabel.font = [UIFont systemFontOfSize:16.0f];
    [self.runButton setBackgroundImage:[UIImage imageNamed:@"run_button"] forState:UIControlStateNormal];
    [self.runButton setBackgroundImage:[UIImage imageNamed:@"run_button_selection"] forState:UIControlStateHighlighted];
    [self.bottomView addSubview:self.runButton];
    [self.runButton addTarget:self action:@selector(onRunButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    rect =  CGRectMake(0, 0, 40, 40);
    self.photoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.photoButton.frame = rect;
    self.photoButton.centerX = self.bottomView.width * 3 / 4;
    self.photoButton.centerY = self.runButton.centerY;
    self.photoButton.backgroundColor = self.runButton.backgroundColor;
    [self.photoButton setImage:[UIImage imageNamed:@"run_photo"] forState:UIControlStateNormal];
    [self.photoButton setImage:[UIImage imageNamed:@"run_photo_selection"] forState:UIControlStateHighlighted];
    [self.bottomView addSubview:self.photoButton];
    
    [self.photoButton addTarget:self action:@selector(onClickPhotoButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.shareButton.frame = rect;
    self.shareButton.centerX = self.bottomView.width / 4;
    self.shareButton.centerY = self.runButton.centerY;
    self.shareButton.backgroundColor = self.runButton.backgroundColor;
    [self.shareButton setBackgroundImage:[UIImage imageNamed:@"run_button"] forState:UIControlStateNormal];
    [self.shareButton setImage:[UIImage imageNamed:@"news_share"] forState:UIControlStateNormal];
//    [self.shareButton setImage:[UIImage imageNamed:@"run_photo_selection"] forState:UIControlStateHighlighted];
    self.shareButton.hidden = YES;
    [self.bottomView addSubview:self.shareButton];
    
    [self.shareButton addTarget:self action:@selector(onClickShareButton:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)initMapView
{
    CGRect rect = CGRectMake(0, 0, self.view.width,self.bottomView.top);
    self.runMapView = [[BMKMapView alloc] initWithFrame:rect];
    self.runMapView.showsUserLocation = YES;
    self.runMapView.delegate = self;
    self.runMapView.showMapScaleBar = YES;
    [self.view insertSubview:self.runMapView belowSubview:self.bottomView];
    
    [BMKLocationService setLocationDistanceFilter:20.0f];
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyBestForNavigation];
    self.locationService = [[BMKLocationService alloc] init];
    self.locationService.delegate = self;
    [self.locationService startUserLocationService];
}

- (void)updateDistanceLabelWithDistance:(CGFloat)distance
{
    self.distanceLabel.text = [[NSString alloc] initWithFormat:@"%.01f",distance/1000];
    self.distanceLabel.width = [self.distanceLabel sizeThatFits:CGSizeZero].width;
    self.distanceLabel.right = self.view.width / 2;
    self.distanceTagLabel.right = self.distanceLabel.left - 10;
    
    CurrentUser *user = [CurrentUser shareInstance];
    
    NSInteger calorie = user.weight * distance * 1.036 / 1000;
    self.calorieLabel.text = [[NSString alloc] initWithFormat:@"卡路里消耗了%d大卡",calorie];
}

- (void)onRunButtonClick:(UIButton *)sender
{
    if (!self.isRunning) {
        
        if ([CurrentUser shareInstance].weight == 0) {
            [self showText:@"请先设置体重"];
            return;
        }
        
        self.runDistance = 0.0f;
        self.runTime = 0;
        self.runTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(onRunTimer:) userInfo:nil repeats:YES];
        
        [sender setTitle:@"跑步结束" forState:UIControlStateNormal];
        self.isRunning = YES;
        [self.locationService startUserLocationService];
        self.navigationItem.rightBarButtonItem = nil;
        
        self.shareButton.hidden = YES;
    }else {
        
        [self.runTimer invalidate];
        
        [sender setTitle:@"跑步开始" forState:UIControlStateNormal];
        self.isRunning = NO;
        [self.locationService stopUserLocationService];
        
        self.shareButton.hidden = NO;
        
        UIButton *rightButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
        rightButton1.frame = CGRectMake(0, 0, 60, 26);
        [rightButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [rightButton1 setTitle:@"收藏" forState:UIControlStateNormal];
        [rightButton1 addTarget:self action:@selector(saveRunMap) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithCustomView:rightButton1];
        self.navigationItem.rightBarButtonItem = rightItem1;
    }
}

- (void)saveRunMap
{
    UIImageWriteToSavedPhotosAlbum([self.runMapView takeSnapshot], nil, nil, nil);
    
    [self showText:@"保存完成"];
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [self.runMapView updateLocationData:userLocation];
    
    if (!self.haveSetCenter) {
        CLLocationCoordinate2D coordinate = userLocation.location.coordinate;
        BMKCoordinateSpan span = BMKCoordinateSpanMake(0.003f, 0.003f);
        BMKCoordinateRegion region = BMKCoordinateRegionMake(coordinate, span);
        [self.runMapView setRegion:region];
        
        self.haveSetCenter = YES;
        
        if (!self.isRunning) {
            [self.locationService stopUserLocationService];
        }
    }
    if (self.isRunning) {
        if (!self.locationArray) {
            self.locationArray = [NSMutableArray array];
            [self.locationArray addObject:userLocation.location];
            
        }else {
            CLLocation *location = self.locationArray.lastObject;
            CLLocationDistance distance = [location distanceFromLocation:userLocation.location];
            if (distance >= 20) {
                [self.locationArray addObject:userLocation.location];
                
                [self addRunLine];
                
                self.runDistance += distance;
            }
        }
    }
}

- (void)addRunLine
{
    [self.runMapView removeOverlays:self.runMapView.overlays];
    
    CLLocationCoordinate2D* coors = (CLLocationCoordinate2D *)malloc(self.locationArray.count * sizeof(CLLocationCoordinate2D));
    for (NSInteger i =0;i<self.locationArray.count;i++){
        CLLocation *location = [self.locationArray objectAtIndex:i];
        coors[i].latitude = location.coordinate.latitude;
        coors[i].longitude = location.coordinate.longitude;
    }
    
    BMKPolyline* polyline = [BMKPolyline polylineWithCoordinates:coors count:self.locationArray.count];
    [self.runMapView addOverlay:polyline];
}

- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView *lineView = [[BMKPolylineView alloc] initWithPolyline:overlay];
        lineView.fillColor = [UIColor redColor];
        lineView.strokeColor = [UIColor redColor];
        lineView.lineWidth = 3.0f;
        return lineView;
    }
    return nil;
}

-(void)setRunDistance:(CGFloat)runDistance
{
    _runDistance = runDistance;
    
    [self updateDistanceLabelWithDistance:runDistance];
}

- (void)setRunTime:(NSInteger)runTime
{
    _runTime = runTime;
    
    NSInteger hour = runTime / (60 * 60);
    NSInteger minute = (runTime - hour * 60 * 60)/60;
    NSInteger second = (runTime - hour * 60 * 60 - minute * 60);
    
    if (hour > 0) {
        self.timeLabel.text = [[NSString alloc] initWithFormat:@"计时 %02d:%02d:%02d",hour,minute,second];
    }else {
        self.timeLabel.text = [[NSString alloc] initWithFormat:@"计时 %02d:%02d",minute,second];
    }
}

- (void)onRunTimer:(NSTimer *)timer
{
    self.runTime ++;
}

#pragma mark - 照相
- (void)onClickPhotoButton:(id)sender
{
    BOOL rearCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];//前
    BOOL frontCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    if (!rearCameraAvailable && !frontCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此设备相机不可用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeCamera;//调用相册
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

//点击use调用的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //要上传的图片
    UIImage *photoImage = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [self uploadImage:photoImage];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImage:(UIImage *)image
{
    [self showHUD];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.3f);
    [PhotoNet uploadPhotoData:imageData successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hideHUD];
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"上传成功！" time:2];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHUD];
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

#pragma mark - 分享
- (void)onClickShareButton:(id)sender
{
    if (self.shareUrl.length) {
        [self share];
        return;
    }
    
    [self showText:@"上传图片中..."];
    [ShareNet shareWithImage:UIImageJPEGRepresentation([self.runMapView takeSnapshot], 0.3) successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hideHUD];
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            self.shareUrl = [responseObject objectForKey:@"data"];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self share];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHUD];
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)share
{
    //构造分享内容
    NSString *content = [NSString stringWithFormat:@"我今天运动了%ld秒，消耗了%ld大卡，快来看看吧", (long)self.runTime, (long)[CurrentUser shareInstance].weight * self.runDistance * 1.036 / 1000];
    
    id<ISSContent> publishContent = [ShareSDK content:content
                                       defaultContent:nil
                                                image:[ShareSDK pngImageWithImage:[[self.runMapView takeSnapshot] reSizeImageToSize:CGSizeMake(self.view.width/6, self.view.width/6)]]
                                                title:@"跑步"
                                                  url:self.shareUrl
                                          description:content
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    
    NSArray *shareList = [ShareSDK getShareListWithType:ShareTypeSinaWeibo,ShareTypeQQ,ShareTypeWeixiSession,ShareTypeWeixiTimeline, nil];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:shareList
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [self showText:[NSString stringWithFormat:@"%@", [error errorDescription]]];
                                    });
                                    
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                }
                            }];
}

@end
